package com.bupt.websocket.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.bupt.websocket.bean.CreateGroup;
import com.bupt.websocket.bean.WebSocketResult;
import com.bupt.websocket.config.ValProperties;
import com.bupt.websocket.service.UserService;
import com.bupt.websocket.service.impl.WebPush;
import com.bupt.websocket.utils.DisposableClient;
import com.bupt.websocket.utils.IkariUtils;
import com.bupt.websocket.utils.JwtToken;
import com.jyt.message.Message;
import com.jyt.message.MessageConfig;
import com.jyt.util.MySerializable;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.stereotype.Controller;
import org.springframework.web.HttpSessionRequiredException;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;
import java.util.Random;

/**
 * Created by ikariyui on 2018/1/15.
 */
@Controller
public class SomeController {

    @Value("${backhend_server_ip}")
    public String BACKHEND_SERVER_IP;

    @Autowired
    public UserService userService;

    //1-通过姓名查找陌生人；
    //2-获取群组成员列表；
    //3-获取自己的详细信息；
    //4-修改自己的用户信息；
    //5-创建群组；
    //6-获取自己所在的群；
    //7-添加群成员；
    //8-删除群成员；
    //9-退群；
    //10-修改群名称；

    //0-test
    @RequestMapping("hellotest")
    @ResponseBody
    public String helloTest(){

        return "{\"success\":\"good\"}";
    }

    //1-通过姓名查找陌生人；
    @RequestMapping("searchFriendByName")
    @ResponseBody
    public String searchFriendByName(@RequestParam String uid, @RequestParam String searchName) {
        String entityName = uid + "searchFriendByName";
        String requestType = "searchFriendByName";
        String request = "{'uid':'" + uid + "','searchName':'" + searchName + "'}";
        String serviceName = "sys_groups";
        String responseType = "searchFriendByName";

        String response = requestToBack(entityName, requestType, request, serviceName, responseType);
        /*Object parse = JSONArray.parse(response);
        response = JSON.toJSONString(parse);*/
        return response;
    }

    //2-获取群组成员列表
    @RequestMapping("getGroupMembers")
    @ResponseBody
    public String getGroupMembers(@RequestParam String uid, @RequestParam String gid) {
        String entityName = uid + "getGroupMembers";
        String requestType = "getGroupMembers";
        String request = "{'uid':'" + uid + "','gid':'" + gid + "'}";
        String serviceName = "sys_groups";
        String responseType = "getGroupMembers";

        String response = requestToBack(entityName, requestType, request, serviceName, responseType);
        /*Object parse = JSONArray.parse(response);
        response = JSON.toJSONString(parse);*/
        return response;
    }

    //3-获取自己的详细信息；
    @RequestMapping("fetchUserInfo")
    @ResponseBody
    public String fetchUserInfo(@RequestParam String uid) {
        String entityName = uid + "fetchUserInfoById";
        String requestType = "fetchUserInfoById";
        String request = "{'id':'" + uid + "'}";
        String serviceName = "sys_userinfo";
        String responseType = "fetchUserInfoById";

        String response = requestToBack(entityName, requestType, request, serviceName, responseType);
        /*Object parse = JSON.parse(response);
        response = JSON.toJSONString(parse);*/
        return response;
    }

    //4-修改自己的用户信息；
    @RequestMapping("modifyUserInfo")
    @ResponseBody
    public String modifyUserInfo(@RequestParam String uid,
                                 @RequestParam(value = "passwd") String passwd,
                                 @RequestParam(value = "email") String email,
                                 @RequestParam(value = "phone") String phone) {
        String entityName = uid + "modifyUserInfo";
        String requestType = "modifyUserInfo";
        String request = "{'id':'" + uid + "',"
                + "'passwd':'" + passwd + "',"
                + "'phone':'" + phone + "',"
                + "'email':'" + email + "'}";
        String serviceName = "sys_userinfo";
        String responseType = "modifyUserInfo";

        String response = requestToBack(entityName, requestType, request, serviceName, responseType);
        /*Object parse = JSONArray.parse(response);
        response = JSON.toJSONString(parse);*/

        return response;
    }


    //5-创建群组；
    @RequestMapping("createGroup")
    @ResponseBody
    public WebSocketResult createGroup(@RequestBody CreateGroup createGroup) {
        String uid = createGroup.getUid();
        String s = JSON.toJSONString(createGroup);
        String from = uid;
        String requestType = "createGroup";
        String request = s;
        String to = "sys_groups";

        boolean isSuccess = IkariUtils.sendViWebPush(from, to, requestType, request);
       // return new WebSocketResult(isSuccess);
        return new WebSocketResult(isSuccess);
    }

    //6-获取群组列表；
    @RequestMapping("getGroupListOfUser")
    @ResponseBody
    public String getGroupListOfUser(@RequestParam String uid) {

        String entityName = uid + "getGroupListOfUser";
        String requestType = "getGroupListOfUser";
        String request = "{'uid':'" + uid + "'}";
        String serviceName = "sys_groups";
        String responseType = "getGroupListOfUser";

        String response = requestToBack(entityName, requestType, request, serviceName, responseType);
        //Object parse = JSONArray.parse(response);
        //response = JSON.toJSONString(parse);

        return response;
    }

    //7-添加群成员；
    @RequestMapping("addMemberToGroup")
    @ResponseBody
    public WebSocketResult addMemberToGroup(@RequestParam String gid, @RequestParam String mid, @RequestParam String uid) {

        String request = "{'gid':'" + gid + "','mid':'" + mid + "','uid':'" + uid + "'}";
        boolean isSuccess = IkariUtils.sendViWebPush(uid, "sys_groups", "addMemberToGroup", request);
        return new WebSocketResult(isSuccess);
    }

    //8-删除群成员；
    @RequestMapping("delMemberFromGroup")
    @ResponseBody
    public WebSocketResult deleteMemberFromGroup(@RequestParam String gid, @RequestParam String mid, @RequestParam String uid) {


        String request = "{'gid':'" + gid + "','mid':'" + mid + "','uid':'" + uid + "'}";
        boolean isSuccess = IkariUtils.sendViWebPush(uid, "sys_groups", "delMember", request);
        return new WebSocketResult(isSuccess);
    }

    //9-退群；
    @RequestMapping("quitGroup")
    @ResponseBody
    public WebSocketResult quitGroup(@RequestParam String gid, @RequestParam String uid) {

        String request = "{'gid':'" + gid + "','mid':'" + uid + "','uid':'" + uid + "'}";
        boolean isSuccess = IkariUtils.sendViWebPush(uid, "sys_groups", "delMember", request);
        return new WebSocketResult(isSuccess);
    }

    //10-修改群名称；
    @RequestMapping("modifyGroupName")
    @ResponseBody
    public WebSocketResult modifyGroupName(@RequestParam String groupid, @RequestParam String groupname, @RequestParam String uid) {



        String request = "{'groupid':'" + groupid + "','groupname':'" + groupname + "','uid':'" + uid + "'}";
        boolean isSuccess = IkariUtils.sendViWebPush(uid, "sys_groups", "modifyGroupName", request);
        return new WebSocketResult(isSuccess);
    }

    public String requestToBack(String entityName, String requestType, String request, String serviceName, String responseType) {
        Random random = new Random();
        String newEntityName = entityName + random.nextInt(30000);

        DisposableClient clientWeb = new DisposableClient(BACKHEND_SERVER_IP, MessageConfig.server_name, newEntityName, responseType);


        //注册客户端
        clientWeb.register(newEntityName);
        byte[] bs;
        bs = MySerializable.object_bytes(request);
        Message msg = new Message(newEntityName, serviceName, requestType, bs);
        //Message msg = new Message(entityName,"clientB","msg",bs);
        //发送请求;
        clientWeb.send(msg);
        //启动监听;
        String theResult = clientWeb.workString();
        clientWeb.unregister(newEntityName);
        clientWeb.shutdown();
        return theResult;
    }

}
